from django.core.exceptions import ValidationError
from django.http.response import Http404
from django.shortcuts import get_object_or_404 as _get_object_or_404
from django_filters.rest_framework import DjangoFilterBackend
from loguru import logger
from mongoengine.queryset.base import BaseQuerySet
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.request import Request
from rest_framework.settings import api_settings
from rest_framework.viewsets import ViewSetMixin
from . import mixins
from .generics import GenericAPIView
from .response import SuccessResponse
from apps.vadmin.utils.export_excel import export_excel_save_model, excel_to_data
from apps.vadmin.utils.request_util import get_verbose_name

class GenericViewSet(ViewSetMixin, GenericAPIView):
    pass

class ReadOnlyModelViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):
    pass


class RUDModelViewSet(
    mixins.CreateModelMixin,
    mixins.RetrieveModelMixin,
    mixins.UpdateModelMixin,
    mixins.DestroyModelMixin,
    GenericViewSet,
):
    pass


class RUDLModelViewSet(
    # mixins.CreateModelMixin,
    mixins.RetrieveModelMixin,
    mixins.UpdateModelMixin,
    mixins.DestroyModelMixin,
    mixins.ListModelMixin,
    GenericViewSet,
):
    pass


class ModelViewSet(
    mixins.CreateModelMixin,
    mixins.RetrieveModelMixin,
    mixins.UpdateModelMixin,
    mixins.DestroyModelMixin,
    mixins.ListModelMixin,
    GenericViewSet,
):
    pass


class MongoModelViewSet(
    mixins.CreateModelMixin,
    mixins.RetrieveModelMixin,
    mixins.UpdateModelMixin,
    mixins.DestroyModelMixin,
    mixins.ListModelMixin,
):
    pass


class CustomModelViewSet(
    ModelViewSet,
    mixins.TableSerializerMixin,
    mixins.ImportSerializerMixin,
    mixins.ExportSerializerMixin,
):
    """
    自定义的ModelViewSet:
    (1)默认分页器就为统一分页器op_drf.pagination.Pagination
    (1)默认使用统一标准返回格式
    (1)默认支持高级搜索
    (1)默认支持生成前端动态table的option
    (1)ORM性能优化, 尽可能使用values_queryset形式
    """

    values_queryset = None
    ordering_fields = "__all__"

    def get_queryset(self):
        if getattr(self, "values_queryset", None):
            return self.values_queryset
        return super().get_queryset()

    def export(self, request: Request, *args, **kwargs):
        '''
        导出功能
        :param request:
        :param args:
        :param kwargs:
        :return:
        '''
        assert self.export_field_data, "'%s' 请配置对应的导出模板字段。" % self.__class__.__name__
        queryset = self.filter_queryset(self.get_queryset())
        data = self.export_serializer_class(queryset, many=True).data
        return SuccessResponse(
            export_excel_save_model(
                request,
                self.export_field_data,
                data,
                f"导出{get_verbose_name(queryset)}.xls",
            )
        )
